package priv.pfz.basedao.query;

import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nullable;

/**
 * @author yyjxp
 * 2024/1/28 20:26
 */
public class StringColumn<Query extends BaseQuery<Query>> extends BaseColumn<String, Query> {

    public StringColumn(Query query, String fieldName, String columnName) {
        super(query, fieldName, columnName);
    }

    @Override
    protected boolean isValueEmpty(String value) {
        return StringUtils.isBlank(value);
    }

    /**
     * xxx = ''
     */
    public Query isEmpty() {
        return commonKeyOp(OpType.IS_EMPTY);
    }

    /**
     * xxx != ''
     */
    public Query notEmpty() {
        return commonKeyOp(OpType.NOT_EMPTY);
    }

    /**
     * xxx LIKE CONCAT('%', 'abc', '%')
     */
    public Query like(@Nullable String value) {
        return commonLikeOp(value, OpType.LIKE);
    }

    /**
     * xxx NOT LIKE CONCAT('%', 'abc', '%')
     */
    public Query notLike(@Nullable String value) {
        return commonLikeOp(value, OpType.NOT_LIKE);
    }

    /**
     * xxx LIKE CONCAT('abc', '%')
     */
    public Query startWith(@Nullable String value) {
        return commonLikeOp(value, OpType.START_WITH);
    }

    /**
     * xxx LIKE CONCAT('%', 'abc')
     */
    public Query endWith(@Nullable String value) {
        return commonLikeOp(value, OpType.END_WITH);
    }

    private Query commonLikeOp(String value, OpType opType) {
        if (isValueEmpty(value)) {
            return query;
        }
        String placeholder = query.addValue(value);
        Condition<String> condition = new Condition<>();
        condition.setFieldName(fieldName);
        condition.setOpType(opType);
        condition.addValue(value);
        condition.setSqlFormat(columnSql + " " + opType.getOp() + placeholder + opType.getOp2());
        query.addCondition(condition);
        return query;
    }
}
